<template>
  <div class="admin-container h-screen bg-gray-50 flex">
    <!-- 侧边栏 -->
    <div class="sidebar w-64 bg-gray-900 flex flex-col">
      <!-- 侧边栏头部 -->
      <div class="sidebar-header p-6 border-b border-gray-800">
        <div class="flex items-center">
          <div
            class="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center mr-3"
          >
            <Icon name="dashboard" size="24" class="text-white" />
          </div>
          <h1 class="text-xl font-bold text-white">管理后台</h1>
        </div>
      </div>

      <!-- 导航菜单 -->
      <nav class="flex-1 px-4 py-6">
        <ul class="space-y-2">
          <li>
            <button
              @click="handleMenuSelect('dashboard')"
              :class="[
                'w-full flex items-center px-4 py-3 rounded-lg text-left transition-all duration-200',
                activeMenu === 'dashboard'
                  ? 'bg-blue-600 text-white shadow-lg'
                  : 'text-gray-300 hover:bg-gray-800 hover:text-white',
              ]"
            >
              <Icon name="dashboard" size="20" class="mr-3" />
              仪表盘
            </button>
          </li>
          <li>
            <button
              @click="handleMenuSelect('users')"
              :class="[
                'w-full flex items-center px-4 py-3 rounded-lg text-left transition-all duration-200',
                activeMenu === 'users'
                  ? 'bg-blue-600 text-white shadow-lg'
                  : 'text-gray-300 hover:bg-gray-800 hover:text-white',
              ]"
            >
              <Icon name="user" size="20" class="mr-3" />
              用户管理
            </button>
          </li>
          <li>
            <button
              @click="handleMenuSelect('conversations')"
              :class="[
                'w-full flex items-center px-4 py-3 rounded-lg text-left transition-all duration-200',
                activeMenu === 'conversations'
                  ? 'bg-blue-600 text-white shadow-lg'
                  : 'text-gray-300 hover:bg-gray-800 hover:text-white',
              ]"
            >
              <Icon name="chat" size="20" class="mr-3" />
              对话管理
            </button>
          </li>
        </ul>
      </nav>

      <!-- 侧边栏底部 -->
      <div class="sidebar-footer p-4 border-t border-gray-800">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <div
              class="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center mr-3"
            >
              <Icon name="user" size="16" class="text-white" />
            </div>
            <span class="text-sm font-medium text-gray-300">
              {{ user && (user.nickname || user.username) }}
            </span>
          </div>
          <button
            @click="logout"
            class="px-2 p-1.5 text-gray-400 bg-gray-800 rounded-md hover:text-white transition-colors text-sm"
          >
            <LoginOutlined class="mr-1" /> 退出
          </button>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content flex-1 flex flex-col">
      <!-- 顶部导航栏 -->
      <header class="bg-white border-b border-gray-200 px-8 py-4">
        <div class="flex items-center justify-between">
          <h2 class="text-2xl font-bold text-gray-900">{{ getPageTitle() }}</h2>
          <div class="flex items-center space-x-4">
            <span class="text-sm text-gray-600">欢迎回来，</span>
            <span class="font-medium text-gray-900">{{
              user && (user.nickname || user.username)
            }}</span>
          </div>
        </div>
      </header>

      <!-- 主要内容 -->
      <main class="flex-1 p-8 overflow-y-auto">
        <!-- 仪表盘 -->
        <div v-if="activeMenu === 'dashboard'" class="dashboard space-y-8">
          <!-- 统计卡片 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div class="card p-6">
              <div class="flex items-center">
                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mr-4">
                  <Icon name="user" size="24" class="text-blue-600" />
                </div>
                <div>
                  <p class="text-sm font-medium text-gray-600">总用户数</p>
                  <p class="text-2xl font-bold text-gray-900">{{ dashboardData.userCount }}</p>
                </div>
              </div>
            </div>

            <div class="card p-6">
              <div class="flex items-center">
                <div
                  class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mr-4"
                >
                  <Icon name="chat" size="24" class="text-green-600" />
                </div>
                <div>
                  <p class="text-sm font-medium text-gray-600">总对话数</p>
                  <p class="text-2xl font-bold text-gray-900">
                    {{ dashboardData.conversationCount }}
                  </p>
                </div>
              </div>
            </div>

            <div class="card p-6">
              <div class="flex items-center">
                <div
                  class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mr-4"
                >
                  <Icon name="send" size="24" class="text-purple-600" />
                </div>
                <div>
                  <p class="text-sm font-medium text-gray-600">总消息数</p>
                  <p class="text-2xl font-bold text-gray-900">{{ dashboardData.messageCount }}</p>
                </div>
              </div>
            </div>

            <div class="card p-6">
              <div class="flex items-center">
                <div
                  class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center mr-4"
                >
                  <Icon name="user" size="24" class="text-orange-600" />
                </div>
                <div>
                  <p class="text-sm font-medium text-gray-600">活跃用户</p>
                  <p class="text-2xl font-bold text-gray-900">{{ getActiveUserCount() }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 数据表格 -->
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- 最近用户 -->
            <div class="card">
              <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">最近注册用户</h3>
              </div>
              <div class="p-6">
                <div class="overflow-x-auto">
                  <table class="w-full">
                    <thead>
                      <tr class="border-b border-gray-200">
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">
                          用户名
                        </th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">邮箱</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">
                          注册时间
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        v-for="user in dashboardData.recentUsers"
                        :key="user.id"
                        class="border-b border-gray-100"
                      >
                        <td class="py-3 px-4 text-sm text-gray-900">{{ user.username }}</td>
                        <td class="py-3 px-4 text-sm text-gray-600">{{ user.email }}</td>
                        <td class="py-3 px-4 text-sm text-gray-600">
                          {{ formatTime(user.createTime) }}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <!-- 最近对话 -->
            <div class="card">
              <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">最近对话</h3>
              </div>
              <div class="p-6">
                <div class="overflow-x-auto">
                  <table class="w-full">
                    <thead>
                      <tr class="border-b border-gray-200">
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">标题</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">模型</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">
                          创建时间
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        v-for="conversation in dashboardData.recentConversations"
                        :key="conversation.id"
                        class="border-b border-gray-100"
                      >
                        <td class="py-3 px-4 text-sm text-gray-900">{{ conversation.title }}</td>
                        <td class="py-3 px-4 text-sm text-gray-600">{{ conversation.model }}</td>
                        <td class="py-3 px-4 text-sm text-gray-600">
                          {{ formatTime(conversation.createTime) }}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户管理 -->
        <div v-if="activeMenu === 'users'" class="users-management space-y-6">
          <!-- 搜索工具栏 -->
          <div class="flex items-center space-x-4">
            <div class="flex-1 max-w-md">
              <input
                v-model="userSearch"
                type="text"
                placeholder="搜索用户..."
                class="input"
                @input="searchUsers"
              />
            </div>
            <button @click="searchUsers" class="btn-primary">搜索</button>
          </div>

          <!-- 用户表格 -->
          <div class="card overflow-hidden">
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">ID</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">用户名</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">邮箱</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">昵称</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">状态</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">注册时间</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="user in usersData.records"
                    :key="user.id"
                    class="border-b border-gray-100 hover:bg-gray-50"
                  >
                    <td class="py-4 px-6 text-sm text-gray-900">{{ user.id }}</td>
                    <td class="py-4 px-6 text-sm text-gray-900">{{ user.username }}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">{{ user.email }}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">{{ user.nickname }}</td>
                    <td class="py-4 px-6">
                      <span
                        :class="[
                          'inline-flex px-2 py-1 text-xs font-medium rounded-full',
                          user.status === 1
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800',
                        ]"
                      >
                        {{ user.status === 1 ? '正常' : '禁用' }}
                      </span>
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-600">
                      {{ formatTime(user.createTime) }}
                    </td>
                    <td class="py-4 px-6 text-sm">
                      <div class="flex items-center space-x-2">
                        <button @click="toggleUserStatus(user)" class="btn-text text-sm">
                          {{ user.status === 1 ? '禁用' : '启用' }}
                        </button>
                        <button @click="deleteUser(user)" class="btn-danger text-sm px-3 py-1">
                          删除
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 分页 -->
            <div class="px-6 py-4 border-t border-gray-200">
              <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">共 {{ usersData.total }} 条记录</div>
                <div class="flex items-center space-x-2">
                  <button
                    @click="userPagination.current > 1 && (userPagination.current--, fetchUsers())"
                    :disabled="userPagination.current === 1"
                    class="btn-secondary px-3 py-1 text-sm disabled:opacity-50"
                  >
                    上一页
                  </button>
                  <span class="text-sm text-gray-600">
                    {{ userPagination.current }} /
                    {{ Math.ceil(usersData.total / userPagination.size) }}
                  </span>
                  <button
                    @click="
                      userPagination.current < Math.ceil(usersData.total / userPagination.size) &&
                        (userPagination.current++, fetchUsers())
                    "
                    :disabled="
                      userPagination.current >= Math.ceil(usersData.total / userPagination.size)
                    "
                    class="btn-secondary px-3 py-1 text-sm disabled:opacity-50"
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 对话管理 -->
        <div v-if="activeMenu === 'conversations'" class="conversations-management space-y-6">
          <!-- 搜索工具栏 -->
          <div class="flex items-center space-x-4">
            <div class="flex-1 max-w-md">
              <input
                v-model="conversationSearch"
                type="text"
                placeholder="搜索对话..."
                class="input"
                @input="searchConversations"
              />
            </div>
            <button @click="searchConversations" class="btn-primary">搜索</button>
          </div>

          <!-- 对话表格 -->
          <div class="card overflow-hidden">
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">ID</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">标题</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">用户ID</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">模型</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">创建时间</th>
                    <th class="text-left py-4 px-6 text-sm font-medium text-gray-600">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="conversation in conversationsData.records"
                    :key="conversation.id"
                    class="border-b border-gray-100 hover:bg-gray-50"
                  >
                    <td class="py-4 px-6 text-sm text-gray-900">{{ conversation.id }}</td>
                    <td class="py-4 px-6 text-sm text-gray-900">{{ conversation.title }}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">{{ conversation.userId }}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">{{ conversation.model }}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">
                      {{ formatTime(conversation.createTime) }}
                    </td>
                    <td class="py-4 px-6 text-sm">
                      <div class="flex items-center space-x-2">
                        <button @click="viewConversation(conversation)" class="btn-text text-sm">
                          查看详情
                        </button>
                        <button
                          @click="deleteConversation(conversation)"
                          class="btn-danger text-sm px-3 py-1"
                        >
                          删除
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 分页 -->
            <div class="px-6 py-4 border-t border-gray-200">
              <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">共 {{ conversationsData.total }} 条记录</div>
                <div class="flex items-center space-x-2">
                  <button
                    @click="
                      conversationPagination.current > 1 &&
                        (conversationPagination.current--, fetchConversations())
                    "
                    :disabled="conversationPagination.current === 1"
                    class="btn-secondary px-3 py-1 text-sm disabled:opacity-50"
                  >
                    上一页
                  </button>
                  <span class="text-sm text-gray-600">
                    {{ conversationPagination.current }} /
                    {{ Math.ceil(conversationsData.total / conversationPagination.size) }}
                  </span>
                  <button
                    @click="
                      conversationPagination.current <
                        Math.ceil(conversationsData.total / conversationPagination.size) &&
                        (conversationPagination.current++, fetchConversations())
                    "
                    :disabled="
                      conversationPagination.current >=
                      Math.ceil(conversationsData.total / conversationPagination.size)
                    "
                    class="btn-secondary px-3 py-1 text-sm disabled:opacity-50"
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- 对话详情对话框 -->
    <div
      v-if="conversationDialogVisible"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] overflow-hidden">
        <div class="p-6 border-b border-gray-200">
          <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-900">对话详情</h3>
            <button
              @click="conversationDialogVisible = false"
              class="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M6 18L18 6M6 6l12 12"
                ></path>
              </svg>
            </button>
          </div>
        </div>

        <div class="p-6 overflow-y-auto max-h-[60vh]">
          <div class="space-y-4">
            <MessageBubble
              v-for="message in selectedConversationMessages"
              :key="message.id"
              :message="message"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Icon from '../components/icons/Icon.vue'
import MessageBubble from '../components/MessageBubble.vue'
import api from '../utils/api'

export default {
  name: 'Admin',
  components: {
    Icon,
    MessageBubble,
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    const activeMenu = ref('dashboard')
    const userSearch = ref('')
    const conversationSearch = ref('')
    const conversationDialogVisible = ref(false)
    const selectedConversationMessages = ref([])

    const dashboardData = reactive({
      userCount: 0,
      conversationCount: 0,
      messageCount: 0,
      recentUsers: [],
      recentConversations: [],
    })

    const usersData = reactive({
      records: [],
      total: 0,
    })

    const conversationsData = reactive({
      records: [],
      total: 0,
    })

    const userPagination = reactive({
      current: 1,
      size: 10,
    })

    const conversationPagination = reactive({
      current: 1,
      size: 10,
    })

    const user = computed(() => store.state.user)

    const getPageTitle = () => {
      const titles = {
        dashboard: '仪表盘',
        users: '用户管理',
        conversations: '对话管理',
      }
      return titles[activeMenu.value] || '管理后台'
    }

    const getActiveUserCount = () => {
      return usersData.records.filter((user) => user.status === 1).length
    }

    const formatTime = (time) => {
      if (!time) return ''
      return new Date(time).toLocaleString('zh-CN')
    }

    const handleMenuSelect = (index) => {
      activeMenu.value = index

      switch (index) {
        case 'dashboard':
          fetchDashboard()
          break
        case 'users':
          fetchUsers()
          break
        case 'conversations':
          fetchConversations()
          break
      }
    }

    const fetchDashboard = async () => {
      try {
        const response = await api.get('/admin/dashboard')
        Object.assign(dashboardData, response.data)
      } catch (error) {
        showErrorMessage('获取仪表盘数据失败')
      }
    }

    const fetchUsers = async () => {
      try {
        const response = await api.get('/admin/users', {
          params: {
            current: userPagination.current,
            size: userPagination.size,
            keyword: userSearch.value,
          },
        })
        usersData.records = response.data.records
        usersData.total = response.data.total
      } catch (error) {
        showErrorMessage('获取用户列表失败')
      }
    }

    const fetchConversations = async () => {
      try {
        const response = await api.get('/admin/conversations', {
          params: {
            current: conversationPagination.current,
            size: conversationPagination.size,
            keyword: conversationSearch.value,
          },
        })
        conversationsData.records = response.data.records
        conversationsData.total = response.data.total
      } catch (error) {
        showErrorMessage('获取对话列表失败')
      }
    }

    const searchUsers = () => {
      userPagination.current = 1
      fetchUsers()
    }

    const searchConversations = () => {
      conversationPagination.current = 1
      fetchConversations()
    }

    const toggleUserStatus = async (user) => {
      try {
        if (!confirm(`确定要${user.status === 1 ? '禁用' : '启用'}用户 ${user.username} 吗？`))
          return

        await api.put(`/admin/users/${user.id}/status`, null, {
          params: { status: user.status === 1 ? 0 : 1 },
        })

        showSuccessMessage('操作成功')
        fetchUsers()
      } catch (error) {
        showErrorMessage('操作失败')
      }
    }

    const deleteUser = async (user) => {
      try {
        if (!confirm(`确定要删除用户 ${user.username} 吗？此操作不可恢复！`)) return

        await api.delete(`/admin/users/${user.id}`)
        showSuccessMessage('删除成功')
        fetchUsers()
      } catch (error) {
        showErrorMessage('删除失败')
      }
    }

    const viewConversation = async (conversation) => {
      try {
        const response = await api.get(`/admin/conversations/${conversation.id}/messages`)
        selectedConversationMessages.value = response.data
        conversationDialogVisible.value = true
      } catch (error) {
        showErrorMessage('获取对话详情失败')
      }
    }

    const deleteConversation = async (conversation) => {
      try {
        if (!confirm(`确定要删除对话 "${conversation.title}" 吗？`)) return

        await api.delete(`/admin/conversations/${conversation.id}`)
        showSuccessMessage('删除成功')
        fetchConversations()
      } catch (error) {
        showErrorMessage('删除失败')
      }
    }

    const logout = () => {
      store.dispatch('logout')
      router.push('/login')
    }

    const showSuccessMessage = (message) => {
      if (window.$toast) {
        window.$toast.success(message)
      }
    }

    const showErrorMessage = (message) => {
      if (window.$toast) {
        window.$toast.error(message)
      }
    }

    onMounted(() => {
      fetchDashboard()
    })

    return {
      activeMenu,
      userSearch,
      conversationSearch,
      conversationDialogVisible,
      selectedConversationMessages,
      dashboardData,
      usersData,
      conversationsData,
      userPagination,
      conversationPagination,
      user,
      getPageTitle,
      getActiveUserCount,
      formatTime,
      handleMenuSelect,
      fetchUsers,
      fetchConversations,
      searchUsers,
      searchConversations,
      toggleUserStatus,
      deleteUser,
      viewConversation,
      deleteConversation,
      logout,
    }
  },
}
</script>

<style scoped>
.admin-container {
  height: 100vh;
}

.sidebar {
  width: 16rem;
}

.main-content {
  flex: 1;
}

.card {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.card:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .sidebar {
    width: 4rem;
  }

  .sidebar-header h1,
  .sidebar-header .mr-3,
  .sidebar nav span {
    display: none;
  }

  .sidebar-header {
    padding: 1.5rem;
  }

  .sidebar nav {
    padding: 1rem 0.5rem;
  }

  .sidebar nav button {
    justify-content: center;
    padding: 0.75rem;
  }

  .sidebar nav button .mr-3 {
    margin-right: 0;
  }
}

@media (max-width: 768px) {
  .sidebar {
    position: absolute;
    z-index: 10;
    height: 100%;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.open {
    transform: translateX(0);
  }

  .main-content {
    width: 100%;
  }
}
</style>
